package com.huilan.base.esl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.huilan.base.esl.api.ChatApi;
import com.huilan.base.esl.pojo.ApiResult;
import com.huilan.base.esl.pojo.ApiResultBuild;
import com.huilan.base.esl.pojo.po.chat.ChatPo;
import com.huilan.base.esl.service.fs.EslClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
public class ChatImpl extends BaseImpl implements ChatApi {

    @Override
    public ApiResult send(ChatPo chatPo) {
        List<String> list = sendChat(chatPo,false);
        return ApiResultBuild.success(list);
    }

    @Override
    public ApiResult sendAsync(ChatPo chatPo) {
        List<String> list = sendChat(chatPo,true);
        return ApiResultBuild.success(list.get(0));
    }

    @Override
    public ApiResult sendMulti(List<ChatPo> chatPos) {
        List list = new ArrayList<>(chatPos.size());
        chatPos.forEach(s->{
            List<String> stringList = sendChat(s,false);
            list.add(stringList);

        });
        return ApiResultBuild.success(list);
    }

    @Override
    public ApiResult sendMultiAsync(List<ChatPo> chatPos) {
        List list = new ArrayList<>(chatPos.size());
        chatPos.forEach(s->{
            List<String> stringList = sendChat(s,true);
            list.add(stringList.get(0));

        });
        return ApiResultBuild.success(list);
    }

    private List<String> sendChat(ChatPo chatPo, boolean skipResult){

        String host = getHost();
        if (StrUtil.isNotEmpty(host)){
            host = "@" + host;
        }

        String content = chatPo.getContent();
        if (StrUtil.contains(content,"\\")){
            content = content.replace("\\","\\\\");
        }
        if (StrUtil.contains(content,"|")){
            content = content.replace("|","\\|");
        }

        String command = "chat PROTOCOL|SENDER|RECEIVER|CONTENT|text/plain"
                .replace("PROTOCOL",chatPo.getProtocol())
                .replace("SENDER",chatPo.getSender())
                .replace("RECEIVER",chatPo.getReceiver() + host)
                .replace("CONTENT",content);
        return eslClient.getClient().sendAsyncApiCommand(command, "",skipResult);
    }


}
